package com.atguigu.buffer;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
import java.util.Objects;

/**
 * className: BufferDemo1
 * description:
 * date: 2023/3/9 0009-16:58
 * <p>
 * project: nio
 * package: com.atguigu.buffer
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class BufferDemo1 {

    @Test
    public void buffer01() throws IOException {
        // FileChannel
        RandomAccessFile aFile = new RandomAccessFile(Objects.requireNonNull(BufferDemo1.class.getClassLoader().getResource("01.txt")).getPath(), "rw");
        FileChannel channel = aFile.getChannel();

        // 创建 buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        // 读
        int bytesRead = channel.read(buffer);

        while (bytesRead != -1) {
            // read 模式
            buffer.flip();

            while (buffer.hasRemaining()) {
                System.out.println(((char) buffer.get()));
            }
            buffer.clear();
            bytesRead = channel.read(buffer);
        }

        aFile.close();
    }

    @Test
    public void buffer02() {
        // 创建 buffer
        IntBuffer buffer = IntBuffer.allocate(8);

        // buffer 放
        for (int i = 0; i < buffer.capacity(); i++) {
            int j = 2 * (i + 1);
            buffer.put(j);
        }

        // 重置缓冲区
        buffer.flip();

        // 获取
        while (buffer.hasRemaining()) {
            int value = buffer.get();
            System.out.println(value + " ");
        }
    }
}
